package com.flida.echart.basic.utils;

import com.alibaba.fastjson.JSON;
import com.feilong.core.Validator;
import com.feilong.core.bean.BeanOperationException;
import com.feilong.core.bean.ConvertUtil;
import com.feilong.core.bean.PropertyUtil;
import com.flida.bana.common.util.Pinyin4jUtil;
import com.flida.echart.basic.api.system.entity.Area;
import com.flida.echart.basic.system.service.IAreaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by yzc on 2016/12/15.
 */
@Service("areaHelper")
public class AreaHelper {


    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AreaHelper.class);
    private static final String cityPinYin = "name";//设置city 按照什么字段设置拼音搜索
    @Value("${city_redis_key}")
    public String cityRedisCache;
    @Autowired
    private JRedisUtil jredisUtil;
    @Autowired
    private IAreaService areaService;

    public void setAreaCache() {
        System.out.println("obj:[{}] 启动设置city缓存:[{}]");
        LOGGER.debug("obj:[{}] 启动设置city缓存:[{}]", this.getClass().getName());
        List<Area> areaList = areaService.selectAll();
        if (Validator.isNotNullOrEmpty(areaList)) {
            setAreaCache(cityRedisCache, areaList);
            LOGGER.info("结束---缓存city数据");
        } else {
            LOGGER.error("城市数据导入到redis异常：查询city列表为null");
            throw new RuntimeException("城市数据导入到redis异常：查询city列表为null");
        }

    }

    private void removeKey(Map<String, Object> map) {
        if (Validator.isNotNullOrEmpty(map)) {
            map.remove("class");
            map.remove("seqNum");
            map.remove("firstLetter");
        }

    }

    /**
     * 设置城市列表缓存
     *
     * @param key  缓存key
     * @param data 缓存的数据
     * @throws Exception
     */
    private void setAreaCache(String key, List<Area> data) {

        Validate.notBlank(key, "key [destination bean] not specified!", new Object[0]);
        Validate.notNull(data, "data [origin bean] not specified!", new Object[0]);
        LinkedHashMap<String, Map<String, Object>> areaMap = new LinkedHashMap<>();
        try {
            String pinYinSource = "";
            for (Area product : data) {

                Map<String, Object> subData = PropertyUtil.describe(product);
                if (Validator.isNotNullOrEmpty(subData)) {
                    removeKey(subData);
                    if (subData.containsKey(cityPinYin)) {
                        pinYinSource = (String) subData.get(cityPinYin);
                        Validate.notBlank(pinYinSource, "pinYinSource [destination bean] not specified!", new Object[0]);

                        System.out.println(subData);
                        subData.put("pinyinQ", StringUtils.substringBefore(Pinyin4jUtil.getPinyinToLowerCase(pinYinSource).toLowerCase(), ","));
                        subData.put("pinyinJ", StringUtils.substringBefore(Pinyin4jUtil.getPinyinJianPin(pinYinSource).toLowerCase(), ","));
                        subData.put("pinyinS", Pinyin4jUtil.getPinyinJianPin(pinYinSource).substring(0, 1).toLowerCase());
                    }
                    System.out.println(subData);
                    areaMap.put(product.getId(), subData);
                }
            }
            jredisUtil.del(key);
            jredisUtil.set(key, JSON.toJSONString(areaMap));

        } catch (Exception ex) {
            throw new BeanOperationException(ex);
        }
    }

    /**
     * 获取地区列表缓存
     *
     * @param key 缓存key
     * @return HashMap
     * @throws Exception
     */
    public LinkedHashMap<String, Map<String, Object>> getAreaCache(String key) throws Exception {
        Validate.notBlank(key, "key [destination bean] not null or empty!", new Object[0]);
        Object goodsCacheObj = jredisUtil.get(0, key);
        if (Validator.isNotNullOrEmpty(goodsCacheObj)) {
            String goodsCacheStr = goodsCacheObj.toString();
            try {
                return JSON.parseObject(goodsCacheStr, LinkedHashMap.class);
            } catch (Exception e) {
                throw new BeanOperationException(e);
            }
        } else {
            return null;
        }
    }

    /**
     * 获取地区列表
     *
     * @param areaid 地区Id
     * @return String
     * @throws Exception
     */
    public String getAreaName(String areaid) {

        if (Validator.isNotNullOrEmpty(areaid)) {

            try {
                LinkedHashMap<String, Map<String, Object>> cityList = getAreaCache(cityRedisCache);
                Validate.notNull(cityList, "cityList can\'t be null!", new Object[0]);
                return cityList.get(areaid).get(cityPinYin).toString();
            } catch (Exception ex) {
                throw new BeanOperationException(ex);
            }

        } else {
            return null;
        }

    }


    public List wizard(String field) {

        if (Validator.isNotNullOrEmpty(field)) {
            TreeMap<String, Object> wizard = new TreeMap<>();
            wizardArea(field, wizard);
            return ConvertUtil.toList(wizard);
        } else {
            return null;
        }


    }

    public void wizardArea(String field, TreeMap<String, Object> wizard) {

        Validate.notBlank(field, "field [destination bean] not specified!", new Object[0]);
        Validate.notNull(wizard, "wizard [origin bean] not specified!", new Object[0]);

        String pinyinS = Pinyin4jUtil.getPinyinJianPin(field).substring(0, 1).toLowerCase();
        try {
            LinkedHashMap<String, Map<String, Object>> treeMap = getAreaCache(cityRedisCache);
            match(treeMap, field, wizard);
            match(treeMap, pinyinS, wizard);//首字母匹配

        } catch (Exception e) {
            throw new BeanOperationException(e);
        }
    }

    private void match(LinkedHashMap<String, Map<String, Object>> treeMap, String field, TreeMap<String, Object> wizard) {
        Validate.notBlank(field, "field [destination bean] not specified!", new Object[0]);
        Validate.notNull(treeMap, "treeMap [origin bean] not specified!", new Object[0]);
        Validate.notNull(wizard, "wizard [origin bean] not specified!", new Object[0]);
        Iterator titer = treeMap.entrySet().iterator();
        String mapValue = "";
        while (titer.hasNext()) {

            Map.Entry ent = (Map.Entry) titer.next();
            Map<String, Object> valuet = (Map) ent.getValue();
            if (Validator.isNotNullOrEmpty(valuet)) {
                mapValue = (String) valuet.get("pinyinJ");// 比较简拼
                if (!StringUtils.isBlank(mapValue) && mapValue.toLowerCase().contains(field.toLowerCase())) {
                    wizard.put((String) valuet.get("id"), valuet);
                }

                mapValue = (String) valuet.get("pinyinQ");// 比较全拼
                if (!StringUtils.isBlank(mapValue) && mapValue.toLowerCase().contains(field.toLowerCase())) {
                    wizard.put((String) valuet.get("id"), valuet);
                }

                mapValue = (String) valuet.get("id");// 比较产品code
                if (!StringUtils.isBlank(mapValue) && mapValue.toLowerCase().contains(field.toLowerCase())) {
                    wizard.put((String) valuet.get("id"), valuet);
                }

                mapValue = (String) valuet.get("name");// 比较产品名称
                if (!StringUtils.isBlank(mapValue) && mapValue.contains(field)) {
                    wizard.put((String) valuet.get("id"), valuet);
                }
            }


        }


    }

}
